package com.supermap.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/10/20 15:16
 */
public class HelloWorldClient {

    private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());

    private final ManagedChannel channel;
    private final GreeterGrpc.GreeterBlockingStub blockingStub;
    private final HelloGoGrpc.HelloGoBlockingStub goblockingStub;

    /** Construct client connecting to HelloWorld server at {@code host:port}. */
    public HelloWorldClient(String host, int port) {

        channel = ManagedChannelBuilder
                .forAddress(host, port) // 地址端口
                .usePlaintext()         // 启用 SSL 通信
                .build();
        /**
         * 根据实际需要构造
         */
        blockingStub = GreeterGrpc.newBlockingStub(channel);
        goblockingStub = HelloGoGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    /** Say hello to server. */
    public void greet(String name) {
        logger.info("Will try to greet " + name + " ...");
        HelloRequest request = HelloRequest.newBuilder().setName(name).setSex("女").build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
            return;
        }
        logger.info("Greeting: " + response.getMessage());
    }

    /** Say hello Go to server. */
    public void greetGo(String name) {
        logger.info("Will try to greet " + name + " ...");
        HelloGoRequest helloGoRequest = HelloGoRequest.newBuilder().setName(name).build();
        HelloGoReply helloGoReply;
        try {
            helloGoReply = goblockingStub.sayHelloGo(helloGoRequest);
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
            return;
        }
        logger.info("Greeting: " + helloGoReply.getMessage());
    }

}
